<?php
// $Id$

/**
 * Controller_Admin_Contents 控制器
 */
class Controller_Admin_Contents extends Controller_Abstract
{

	function actionIndex()
	{
		$model = intval($this->_context->model)?intval($this->_context->model):1;// 默认文章内容
		$model_obj = Models::find($model)->getOne();
		// 分页信息
		$pagination = Q::ini('appini/pagination');
		$numPerPage = intval($this->_context->numPerPage)?intval($this->_context->numPerPage):intval($pagination['numPerPage']);
		$currentPage = intval($this->_context->pageNum)?intval($this->_context->pageNum):1;
		$search_title = trim($this->_context->title);
		// 数据查询条件组合
		$find_where = "model = '{$model}'";
		if ($search_title) $find_where .= "and title like '%$search_title%'";
		$data = Contents::find($find_where)
						->limitPage($currentPage,$numPerPage)->order('createtime')
						->get();
		$totle_count = Contents::find($find_where)->getCount();
		
		// 数据加载
		$this->_view['pagination'] = array(
			'totalCount'=>$totle_count,
			'numPerPage'=>$numPerPage,
			'pageNumShown'=>$pagination['pageNumShown'],
			'currentPage'=>$currentPage
		);
		$this->_view['model'] = $model_obj;
		$this->_view['data'] = array(
			'fetch_data'=>$data,
			'context'=>$this->_context
		);
		
		$this->_viewname = trim($model_obj->mcode).'_list';
	}
	/**
	 *
	 * 增加修改
	 */
	function actionModify()
	{
		$model = intval($this->_context->model)?intval($this->_context->model):1;// 默认文章内容
		$model_obj = Models::find($model)->getOne();
		$modify_id = intval($this->_context->mid);
		$return_array = array('statusCode'=>Helper_Dwz::DWZ_STATUS_ERROR,'message'=>'操作失败!');// 服务器响应
		$form = new Form_Contents(url('contents/modify',array('model'=>$model,'mid'=>$modify_id)),$model_obj->mcode);
		// 当操作为修改
		$modify_obj = false;
		if ($modify_id){
			$modify_obj = Contents::find($modify_id)->getOne();
			if (!$modify_obj->id())
			{
				return json_encode(array('statusCode' => Helper_Dwz::DWZ_STATUS_ERROR,'message'=>'您想要修改的信息没有找到!'));
			}
		}
		// 表单处理
		if ($this->_context->isPOST())
		{
			// 参数校验
			if ($form->validate($_POST))
			{
				// 逻辑处理
				$form_values = $form->values();
				$form_values['model'] = $model;
				if (isset($form_values['expire'])) $form_values['expire'] = strtotime($form_values['expire']);
				if ($modify_id && $modify_obj !== false){
					// 修改
					if ($form_values['cateid'] != $modify_obj->cateid)
					{
						$tmp = Categorys::find(intval($form_values['cateid']))->getOne();
						$form_values['catepath'] = $tmp->catepath;
					}
					// 图片转移问题
					if (isset($form_values['imgurl']))
					{
						if ($form_values['imgurl'] != $modify_obj->imgurl){
							// 先转移再删除
							if (is_file($form_values['imgurl'])) 
							{
								$new_filepath = str_replace('uploadfiles/tmp', 'uploadfiles/image', $form_values['imgurl']);
								if (copy($form_values['imgurl'], $new_filepath)){
									if (is_file($new_filepath)){
										// 删除旧文件
										if (is_file($modify_obj->imgurl)){
											unlink($modify_obj->imgurl);
											unlink($form_values['imgurl']);
											$form_values['imgurl'] = $new_filepath;
										}
									}
								}
							}else{
								unset($form_values['imgurl']);
							}
						}
					}else{
						unset($form_values['imgurl']);
					}
					$modify_obj->changeProps($form_values);
				}else{
					// 添加
					$form_values['createtime'] = time();
					if ($form_values['cateid'] != 0)
					{
						$tmp = Categorys::find(intval($form_values['cateid']))->getOne();
						$form_values['catepath'] = $tmp->catepath;
					}
					// 图片转移问题
					if (isset($form_values['imgurl']))
					{
						if (is_file($form_values['imgurl'])) 
						{
							$new_filepath = str_replace('uploadfiles/tmp', 'uploadfiles/image', $form_values['imgurl']);
							if (copy($form_values['imgurl'], $new_filepath)){
								if (is_file($new_filepath)){
									$form_values['imgurl'] = $new_filepath;
									unlink($form_values['imgurl']);
								}
							}
						}
					}
					$modify_obj = new Contents($form_values);
				}
				$modify_obj->save();
				$return_array = array('statusCode' => Helper_Dwz::DWZ_STATUS_OK,'message'=>'操作已成功!','callbackType'=>'forward','navTabId'=>'内容管理','forwardUrl'=>url('contents',array('model'=>$model)));
			}else{
				// 参数校验返回
				foreach ($form->elements() as $element){
					if (!$element->isValid()){
						$err = implode(',', $element->errorMsg());
						$return_array['message'] .= $err.'<br>';
					}
				}
			}
			// 返回数据
			return json_encode($return_array);
		}
		// 原始数据导入
		$cate_data = Categorys::get_category_tree($model);
		unset($cate_data['0']);
		$form->element('cateid')->items = $cate_data;
		// 默认数据导入
		if ($modify_obj !== false)
		{
			$default_value = $modify_obj->toArray();
			$default_value['expire'] = date('Y-m-d',$default_value['expire']);
			$form->import($default_value);
		}
		// 数据加载
		$this->_view['form'] = $form;
		$this->_view['model'] = $model_obj;
		//$this->_viewname = trim($model_obj->mcode).'_form';
	}
	/**
	 *
	 * 删除
	 */
	function actionDelete()
	{
		$delete_id = intval($this->_context->did);
		$model = intval($this->_context->model)?intval($this->_context->model):1;// 默认文章内容
		$return_array = array('statusCode'=>Helper_Dwz::DWZ_STATUS_ERROR,'message'=>'操作失败!');// 服务器响应
		if ($delete_id) {
			$content = Contents::find($delete_id)->getOne();
			if ($content->id())
			{
				// 删除封面图片
				if ($content->imgurl && is_file($content->imgurl))
				{
					@unlink($content->imgurl);
				}
				// 删除内容图片
				if ($content->filepath && is_file($content->filepath)){
					@unlink($content->filepath);
				}
				// 删除内容中含有的图片
				preg_match_all("/src=\"\S*\"/", $content->content , $img_array );
				foreach ($img_array[0] as $item)
				{	
					$filepath = rtrim(ltrim($item,'src=\"/'),'"');
					if (strpos($item,'uploadfiles') && is_file($filepath)) @unlink($filepath);
				}
				// 删除记录
				Contents::meta()->deleteWhere('id = ?',$delete_id);
				$return_array = array('statusCode'=>Helper_Dwz::DWZ_STATUS_OK,'message'=>'删除成功!','callbackType'=>'forward','forwardUrl'=>url('admin::contents',array('model'=>$model)));
			}else{
				$return_array['message'] = '没有找到您要删除的信息';
			}
		}
		return json_encode($return_array);
	}
}